package com.jiuan.transfer.redis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

/**
 * Created by Administrator on 2017/1/4.
 */
/**
 * @Title: RedisUtil.java
 * @Package com.jiuan.transfer.redis
 * @Description: TODO
 * @author Lee
 * @date 2016年8月16日 上午11:37:49
 * @version V1.0
 */

public class ClusterRedisUtil {

    private static String serverInfo = "192.168.12.191:6379,192.168.12.191:6380,192.168.12.191:6381,192.168.12.191:6382,192.168.12.191:6383,192.168.12.191:6384";
    private static Set<HostAndPort> jedisClusterNodes;
    private static JedisCluster jc;

    static{
        initJedisPool();
    }


    private static void resetJedisPool(){
        try {
            jc.close();
        } catch (IOException e) {
            System.out.println("jedisCluster close error");
            e.printStackTrace();
        }
        initJedisPool();
    }
    private static void initJedisPool(){
        jedisClusterNodes = getClusterInfo(serverInfo);
        jc = new JedisCluster(jedisClusterNodes);
    }
    // 获取主机列表
    private static Set<HostAndPort> getClusterInfo(String serverInfo) {
        Set<HostAndPort> set = new HashSet<HostAndPort>();
        if (serverInfo == null || "".equals(serverInfo)) {
            throw new RuntimeException("The serverInfo can not be empty");
        }
        String ipPort[] = serverInfo.split(",");
        int len = ipPort.length;
        for (int i = 0; i < len; i++) {
            String server[] = ipPort[i].split(":");
            set.add(new HostAndPort(server[0], Integer.parseInt(server[1])));
        }
        return set;
    }

    public static String getValue(String key) {
        return jc.get(key);
    }

    public static byte[] getValue(byte[] key) {
        return jc.get(key);
    }

    public static List<String> queryIps(String topic) {
        List<String> ips = new ArrayList<>();
        Set<String> s = jc.smembers(topic);
        for (String id : s) {
            ips.add(jc.get(id));
        }
        return ips;
    }

    public static void main(String[] args) {
        List<String> ips = queryIps("TOPIC_T1");
        System.out.println("ips:"+ArrayUtils.toString(ips.toArray()));

    }

}
